package net.lovesrc.allin.biz.jietu;

import com.google.common.collect.Lists;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.http.Requests;
import com.zhouzhou.fastjava.util.StringKit;
import com.zhouzhou.fastjava.util.ThreadKit;
import net.lovesrc.allin.biz.BaseService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class JieTuService extends BaseService {

    private static final File DIR = new File("D:/git/render-entry");

    public static final File JIE_TU_DIR = new File("d:/data/images/jietu");

    public JieTuAndroidAlipayContext createAndroidAlipayContext(JieTuOuterContext outerContext) {
        String ph1 = PH1[RandomUtils.nextInt(0, PH1.length)];
        BigDecimal amount = outerContext.getAmount();
        String amountString = new DecimalFormat(".00").format(amount);
        return JieTuAndroidAlipayContext.builder()
                .signal(RandomUtils.nextInt(2, 5))
                .carrier(newCarrier(outerContext.getBuyerMobile()))
                .network(newNetwork())
                .time(DateFormatUtils.format(new Date(), "HH:mm"))
                .withNfc(RandomUtils.nextBoolean())
                .withZd(RandomUtils.nextBoolean())
                .withNewMessage(RandomUtils.nextBoolean())
                .withNewPicture(RandomUtils.nextBoolean())
                .power(newAndroidPower())
                .payeeNickname(outerContext.getSellerRealName())
                .payee("*" + outerContext.getSellerRealName().substring(1))
                .payMethod(outerContext.getBuyerPayMethod())
                .amount(amountString)
                .showPh1(true)
                .ph1(ph1)
                .build();
    }

    public JieTuIosAlipayContext createIosAlipayContext(JieTuOuterContext outerContext) {

        boolean showPh1 = RandomUtils.nextBoolean();
        boolean showPh2 = RandomUtils.nextBoolean();
        String ph1 = PH1[RandomUtils.nextInt(0, PH1.length)];
        String ph2 = PH2[RandomUtils.nextInt(0, PH2.length)];
        if (showPh1) {
            // ignore
        } else {
            // 不显示1，那肯定显示2
            showPh2 = true;
        }
        BigDecimal amount = outerContext.getAmount();
        String amountString = new DecimalFormat(".00").format(amount);
        return JieTuIosAlipayContext.builder()
                .signal(RandomUtils.nextInt(2, 5))
                .carrier(newCarrier(outerContext.getBuyerMobile()))
                .network(newNetwork())
                .time(DateFormatUtils.format(new Date(), "HH:mm"))
                .withLock(true)
                .withAlarmClock(RandomUtils.nextBoolean())
                .withGps(RandomUtils.nextBoolean())
                .power(newIOSPower())
                .payee(outerContext.getSellerRealName())
                .payMethod(outerContext.getBuyerPayMethod())
                .amount(amountString)
                .showPh1(showPh1)
                .ph1(ph1)
                .showPh2(showPh2)
                .ph2(ph2)
                .build();
    }

    public File newJieTu(String url, String filename) {
        Exception ex = null;
        for (int i = 0; i < 10; i++) {
            try {
                return doNewJieTu(url, filename);
            } catch (Exception e) {
                ex = e;
            }
        }
        throw new RuntimeException(ex);
    }

    public String randomUserLogo() {
        String html = Requests.get("https://hacpai.com/")
                .executeUtilReturn200()
                .asText();
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("*[data-src]");
        List<String> imgUrls = Lists.newArrayList();
        for (Element img : imgs) {
            String dataSrc = img.attr("data-src");
            if (StringUtils.isNotBlank(dataSrc)) {
                String url = StringKit.extract(dataSrc, "(http.*)\\?");
                imgUrls.add(url + "?imageView2/1/w/80/h/80");
            }
        }
        return imgUrls.get(RandomUtils.nextInt(0, imgUrls.size()));
    }

    private File doNewJieTu(String url, String filename) throws IOException {
        String imgFile = "out/" + filename + ".png";
        {
            File file = new File(DIR, imgFile);
            if (file.exists()) {
                file.delete();
            }
        }
        ProcessBuilder pb = new ProcessBuilder(
                "cmd"
        );
        pb.directory(new File("D:/git/render-entry"));
        Process process = pb.start();
        try {
            PrintWriter out = new PrintWriter(process.getOutputStream());
            out.println("phantomjs render-2-png.js " + url + " out/" + filename);
            out.flush();
            File file = new File(DIR, imgFile);
            for (int i = 0; i < 30; i++) {
                if (file.exists()) {
                    if (file.length() <= 45 * FileUtils.ONE_KB) {
                        throw BizException.messageOf("生成的图片大小，小于 45 KB，可能有问题，请检查");
                    }
                    return file;
                }
                ThreadKit.sleepSeconds(1);
            }
        } finally {
            process.destroy();
        }
        throw BizException.messageOf("截图未生成");
    }

    public static final String[] carriers = new String[]{
            "中国电信", "中国移动", "中国联通"
    };

    private static final String[] PH1 = new String[]{
            "guaguaka-1", "guaguaka-2"
    };

    private static final String[] PH2 = new String[]{
            "huabei-1", "huabei-2", "hongbao-3", "tree-1", "holder-618", "holder-30"
    };

    private String newIOSPower() {
        int rand = RandomUtils.nextInt(0, 100);
        if (rand >= 90) {
            return "power-93";
        } else if (rand >= 60) {
            return "power-60";
        } else if (rand >= 27) {
            return "power-27";
        }
        return "power-19";
    }

    private String newAndroidPower() {
        int rand = RandomUtils.nextInt(0, 100);
        if (rand >= 80) {
            return "power-80";
        } else if (rand >= 68) {
            return "power-68";
        } else if (rand >= 52) {
            return "power-52";
        }
        return "power-52";
    }


    private String newNetwork() {
        int rand = RandomUtils.nextInt(0, 100);
        if (rand >= 80) {
            return "4G";
        } else if (rand >= 70) {
            return "3G";
        } else if (rand >= 30) {
            return "wifi-3";
        } else if (rand >= 10) {
            return "wifi-2";
        } else {
            return "wifi-1";
        }
    }

    private String newCarrier(String mobile) {
        if (Pattern.compile("^134[0-8]\\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|1703|1705|1706|18[2-478])\\d{7,8}$").matcher(mobile).find()) {
            return "中国移动";
        }
        if (Pattern.compile("^(?:13[0-2]|145|15[56]|176|1704|1707|1708|1709|171|18[56])\\d{7,8}|$").matcher(mobile).find()) {
            return "中国联通";
        }
        if (Pattern.compile("^(?:133|153|1700|1701|1702|177|173|18[019])\\d{7,8}$").matcher(mobile).find()) {
            return "中国电信";
        }
        return carriers[RandomUtils.nextInt(0, carriers.length)];
    }

}
